
// 演出的戏剧
// 戏剧项
//    -- name : 戏剧名称
//    -- type : 戏剧类型
// 分为悲剧和喜剧
import {plays, invoices} from "./data.js";


// 重构前的版本
function statement (invoice, plays) {

  let totalAmount = 0;
  let volumeCredits = 0;

  let result = `Statement for ${invoice.customer}\n`;

  const format = new Intl.NumberFormat("en-US",
    {style: "currency", currency: "USD", minimumFractionDigits: 2}).format;

  for (let perf of invoice.performances) {

    const play = plays[perf.playID];

    let thisAmount = 0;

    switch (play.type) {
      case "tragedy":
        thisAmount = 40000;
        if (perf.audience > 30) {
          thisAmount += 1000 * (perf.audience - 30);
        }
        break;
      case "comedy":
        thisAmount = 30000;
        if (perf.audience > 20) {
          thisAmount += 10000 + 500 * (perf.audience - 20);
        }
        break;
      default:
        throw new Error(`unknown type: ${play.type}`);
    }

    // 增加积分
    // add volume credits
    volumeCredits += Math.max(perf.audience - 30, 0);



    // 为什么是除以5呢？ 如果是除以10的话，大于5小于10的结果就是0
    // 如果是喜剧类型的戏剧，每多10个听众就增加1积分
    // add extra credit for every ten comedy attendees
    if ("comedy" === play.type) {
      volumeCredits += Math.floor(perf.audience / 5);
    }
    // 打印订单
    // print line for this order
    result += ` ${play.name}: ${format(thisAmount / 100)} (${perf.audience} seats)\n`;
    totalAmount += thisAmount;

  }

  result += `Amount owed is ${format(totalAmount / 100)}\n`;
  result += `You earned ${volumeCredits} credits \n`;

  return result;
}

for (let invoice of invoices) {
  // 18 19
  let result = statement(invoice, plays);
  console.log(result);
}

